package com.techstar.ats;

import java.net.InetSocketAddress;
import java.util.Objects;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import org.apache.commons.lang3.Validate;

@Setter
@Getter
@NoArgsConstructor
public class ConnectProperties {
	public static final int DEFAULT_CONNECT_TIMEOUT = 60;
	public static final int DEFAULT_READ_TIMEOUT = 15;
	public static final int DEFAULT_WRITE_TIMEOUT = 10;
	public static final int DEFAULT_BOTH_TIMEOUT = 20;
	/**
	 * 连接地址，为空表示0.0.0.0
	 */
	private String hostname;
	/**
	 * 默认端口
	 */
	private int port;

	/**
	 * 本机通信地址
	 */
	private int line;

	/**
	 * 连接超时，单位秒
	 */
	private int connectTimeout = DEFAULT_CONNECT_TIMEOUT;
	/**
	 * 读超时，单位秒
	 */
	private int readTimeout = DEFAULT_READ_TIMEOUT;
	/**
	 * 写超时，单位秒
	 */
	private int writeTimeout = DEFAULT_WRITE_TIMEOUT;
	/**
	 * 读和写都超时，单位秒
	 */
	private int bothTimeout = DEFAULT_BOTH_TIMEOUT;

	/**
	 * 同时在待发队列中的消息数
	 */
	private int traffic = 1;

	private boolean live = true;
	private int systemId = 0xff;
	private int multiply = 1;

	public ConnectProperties(int port, String hostname) {
		this.hostname = hostname;
		this.port = port;
	}

	/**
	 * 在慢速网络，通常不会有这么高的超时设置，为了适应GPRS/LTE等慢速网络，不需要单独配置t1,t2,t3，统一用倍率乘以tx的默认值
	 * 例如：倍率为6，那么t1=90,t2=60,t3=120
	 */
	public void setMultiply(int multiply) {
		Validate.inclusiveBetween(1, 60, multiply);
		this.readTimeout = DEFAULT_READ_TIMEOUT * multiply;
		this.writeTimeout = DEFAULT_WRITE_TIMEOUT * multiply;
		this.bothTimeout = DEFAULT_BOTH_TIMEOUT * multiply;
	}

	public InetSocketAddress toSocketAddress() {
		return Objects.isNull(hostname) ? new InetSocketAddress(port) : new InetSocketAddress(hostname, port);
	}

	@Override
	public boolean equals(Object object) {
		if(this == object) return true;
		if(!(object instanceof ConnectProperties)) return false;
		ConnectProperties that = (ConnectProperties) object;
		return Objects.equals(getHostname(), that.getHostname()) && getPort() == that.getPort() && getLine() == that.getLine();
	}

	@Override
	public int hashCode() {
		return Objects.hash(getHostname(), getPort(), getLine());
	}
}
